package com.example.printlib;

import static android.content.Context.BIND_AUTO_CREATE;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 打印机引擎
 */
public class PrintEngine {
    // 私有构造方法，防止外部直接创建实例
    private PrintEngine() {}

    // 私有静态内部类，持有PrintEngine的实例
    private static class SingletonHolder {
        private static final PrintEngine INSTANCE = new PrintEngine();
    }

    // 提供公共的静态方法获取PrintEngine的实例
    public static PrintEngine getInstance() {
        return SingletonHolder.INSTANCE;
    }
    private Context context;
    private PrintService printService;

    private CopyOnWriteArrayList<PrintService.PrintCallback> printCallbacks = new CopyOnWriteArrayList<>();

    private EngineCallback engineCallback;

    public interface EngineCallback {
        void onEngineStart();
    }

    public void addPrintQueue(String path){
        printService.addPrintQueue(path);
    }
    public void addPrintCallback(PrintService.PrintCallback callback) {
        printService.addPrintCallback(callback);
    }

    public void removePrintCallback(PrintService.PrintCallback callback) {
        printService.removePrintCallback(callback);
    }

    public PrintService.PrintServerStatus getNowState() {
        return printService.getPrinterStatus();
    }

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            PrintService.PrintBinder binder = (PrintService.PrintBinder) service;
            printService = binder.getService();
            engineCallback.onEngineStart();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };


    public void initEngine(Context context,EngineCallback engineCallback) {
        if(this.context!=null){
            engineCallback.onEngineStart();
            return;
        }
        this.context = context;
        this.engineCallback = engineCallback;
        this.context.bindService(new Intent(context, PrintService.class), serviceConnection, BIND_AUTO_CREATE);
    }

    public void unit(Context context) {
        if(this.context!=context)
            return;
        if (printService != null) {
            context.unbindService(serviceConnection);
        }
    }
}
